﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.SalesOneWeb.UserManagement
{
    public partial class ViewRole : SOSecurityPage
    {
        static bool hasPermssions;
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        private int pageNo;

        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));

                if (!IsPostBack)
                {
                    pageNo = 1;
                    SetDataSourceToTypes(structureFacade.GetUserTypes());

                    if (Page.Request.Params["RoleId"] != null)
                    {
                        ddlUserType.SelectedValue = Page.Request.Params["UserType"].ToString();
                        txtPageNo.Text = "1";
                        Search(1, "Upadated DSC");
                        //Search(1);
                    }
                }

                lblError.ForeColor = Color.Black;
                lblError.Text = "";
            }
            catch { MassageSummery("IIS514"); }
        }

        public void SetDataSourceToTypes(List<UserType> userTypes)
        {
            ddlUserType.DataSource = userTypes;
            ddlUserType.DataTextField = "UserTypeName";
            ddlUserType.DataValueField = "UserTypeId";
            ddlUserType.DataBind();

            InsertDDLItems(ddlUserType, "Select...", 0);
            //InsertDDLItems(ddlFrom, "Select All", 1);
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            //ListItem item = new ListItem(Text);
            //ddl.Items.Insert(Position, item);
            ddl.Items.Insert(Position, Text);
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UserManagement/AddUserRoles.aspx?usertype=" + (ddlUserType.SelectedIndex > 0 ? ddlUserType.SelectedValue : ""));
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grdRoles.Rows)
            {
                //RadioButton rbtn = (RadioButton)row.FindControl("RadioButton1");
                CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                if (chk != null)
                {
                    if (chk.Checked)
                        Response.Redirect("~/UserManagement/UpdateRole.aspx?a=u&RoleId=" + chk.ValidationGroup.Split(new char[] { ',' })[0]);
                }
            }
            MassageSummery("IIS503");
        }

        private void SetVisibility(bool _visible)
        {
            btnCreate.Visible = _visible;
            btnUpdate.Visible = _visible;
            btnAssignPermissions.Visible = _visible;

        }

        protected void grdRoles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //DataRowView rowView = (DataRowView)e.Row.DataItem;
                //sourceDocDS.sourceDocDataRow mainLineRow = (sourceDocDS.sourceDocDataRow)rowView.Row;
                //UserRole_aspnet role_aspnet = (UserRole_aspnet)e.Row.DataItem;
                //UserRole role = structureFacade.GetUserRole(role_aspnet.RoleId);

                UserRole role = (UserRole)e.Row.DataItem;
                UserRole_aspnet role_aspnet = structureFacade.GetAspnetUserRole(role.RoleId);

                CheckBox chkEnabled = (CheckBox)e.Row.FindControl("chkEnabled");
                Label lblRoleName = (Label)e.Row.FindControl("lblRoleName");
                CheckBox chkselect = (CheckBox)e.Row.FindControl("chkSelect");

                chkEnabled.ValidationGroup = role.RoleId.ToString() + "," + role.UserTypeId.ToString();
                chkselect.ValidationGroup = role.RoleId.ToString() + "," + role.UserTypeId.ToString();

                if (Page.Request.Params["RoleId"] != null)
                {
                    if (role.RoleId.ToString().Equals(Page.Request.Params["RoleId"].ToString()))
                        chkselect.Checked = true;
                }

                lblRoleName.Text = role_aspnet.RoleName;

                if (role.Status == 1)
                    chkEnabled.Checked = true;

                if (!hasPermssions)
                    chkEnabled.Enabled = false;
            }
        }

        protected void grdRoles_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //int[] cols = (int[])Session["hideCols"];
            int[] cols = { 3, 4, 5 };
            if (cols != null)
            {
                for (int i = 0; i < cols.Length; i++)
                {
                    e.Row.Cells[cols[i]].Visible = false;

                }
            }


        }

        protected void grdRoles_OnDataBound(object sender, EventArgs e)
        {
           List<GridViewStyle> styleList = new List<GridViewStyle> {
                new GridViewStyle{
                    ColumnId = "RoleName",
                    ColumnHeader = "Role Name",
                    ColumnWidth = 100},
                new GridViewStyle{
                    ColumnId = "Is Enabled",
                    ColumnHeader = "Enabled",
                    ColumnWidth = 50},
                new GridViewStyle{
                    ColumnId = "Select",
                    ColumnHeader = "Select",
                    ColumnWidth = 50},
                //new GridViewStyle{
                //    ColumnId = "CompletionTime",
                //    ColumnHeader = "Completion Time",
                //    ColumnWidth = 130}
            };

            int rw = grdRoles.Rows.Count;
            if (rw > 0)
            {
                btnNext.Visible = true;
                if (txtPageNo.Text != "1")
                {
                    btnPrevious.Visible = true;
                }
                else
                {
                    btnPrevious.Visible = false;
                }
                btnGo.Visible = true;
                txtPageNo.Visible = true;

                TableCellCollection columns = grdRoles.HeaderRow.Cells;

                if (styleList != null)
                {
                    for (int i = 0; i < columns.Count; i++)
                    {
                        GridViewStyle style = styleList.SingleOrDefault(p => p.ColumnId.Contains(columns[i].Text));
                        if (style != null)
                        {
                            columns[i].Text = style.ColumnHeader;
                            columns[i].ControlStyle.Width = style.ColumnWidth;
                        }
                    }
                }

            }
            else
            {
                btnNext.Visible = false;
                btnPrevious.Visible = false;
                btnGo.Visible = false;
                txtPageNo.Visible = false;
            }
        }

        protected void ddlUserType_SelectedIndexChanged1(object sender, EventArgs e)
        {
            try
            {
                txtPageNo.Text = "1";
                bool hasRow = Search(1, "");

                if (ddlUserType.SelectedIndex > 0 && hasPermssions && hasRow)
                {
                    btnAssignPermissions.Visible = true;
                    btnUpdate.Visible = true;
                }
                else
                {
                    btnAssignPermissions.Visible = false;
                    btnUpdate.Visible = false;
                }
            }
            catch { MassageSummery("IIS514"); }
        }

        protected void btnAssignPermissions_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grdRoles.Rows)
            {
                //RadioButton rbtn = (RadioButton)row.FindControl("RadioButton1");
                CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                if (chk != null)
                {
                    if (chk.Checked)
                        Response.Redirect("~/UserManagement/AssignPermissions.aspx?RoleId=" + chk.ValidationGroup.Split(new char[] { ',' })[0]);
                }

            }
            MassageSummery("IIS503");
        }

        protected void chkEnabled_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                //Set status to 0

                /*Get ID of the record*/
                CheckBox chkEnabled = (CheckBox)sender;
                string roleID = chkEnabled.ValidationGroup.Split(new char[] { ',' })[0];

                /*Get Other Records */
                short userTypeID = Convert.ToInt16(ddlUserType.SelectedValue);
                /*Insert To DataBase*/
                UserRole userRole = new UserRole();
                userRole.RoleId = new Guid(roleID);
                userRole.UserTypeId = userTypeID;
                if (chkEnabled.Checked)
                    userRole.Status = 1;
                else
                    userRole.Status = 0;

                structureFacade.UpdateUserRole(userRole);
            }
            catch { MassageSummery("IIS514"); }
        }

        public void SetCredentials(StringCollection credential)
        {
            foreach (string item in credential)
            {
                switch (item.ToLower())
                {
                    case "c":
                        btnCreate.Visible = true;
                        break;
                    case "u":
                        //btnUpdate.Visible = true;
                        //btnAssignPermissions.Visible = true;
                        hasPermssions = true;
                        break;
                   
                    default:
                        break;
                }
            }
        }

        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtPageNo.Text != "1")
                {
                    pageNo = int.Parse(txtPageNo.Text) - 1;
                    txtPageNo.Text = pageNo.ToString();

                    Search(pageNo, "");
                }
            }
            catch { MassageSummery("IIS514"); }
        }

        protected void txtGo_Click(object sender, EventArgs e)
        {
            try
            {
                int p = int.Parse(txtPageNo.Text);
                if (p != 0)
                {
                    try
                    {
                        Search(p,"");
                        pageNo = p;
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }
            catch { MassageSummery("IIS505"); }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtPageNo.Text != "1")
                {
                    pageNo = int.Parse(txtPageNo.Text) + 1;
                    txtPageNo.Text = pageNo.ToString();

                }
                else
                {
                    pageNo = 2;
                    txtPageNo.Text = "2";

                }

                Search(pageNo, "");
            }
            catch { MassageSummery("IIS514"); }
        }

        public bool Search(int page, string sortExpression)
        {
            if (ddlUserType.SelectedIndex > 0)
            {
                List<UserRole> roles = structureFacade.GetUserRolesForUserType(Convert.ToInt32(ddlUserType.SelectedValue),page,sortExpression);
                bool IsLastPage = true;
                if (roles.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
                {
                    IsLastPage = (structureFacade.GetUserRolesForUserType(Convert.ToInt32(ddlUserType.SelectedValue), page + 1, sortExpression)).Count > 0 ? false : true;
                }
                //if (roles.Count > 0)
                //    ShowButtons();
                //else
                //    HideButtons();
                if (roles.Count > 0)
                {
                    grdRoles.DataSource = roles;
                    grdRoles.DataBind();
                    grdRoles.Visible = true;
                    SetVisibility(true);

                    if (IsLastPage)
                    {
                        btnNext.Visible = false;
                        if(txtPageNo.Text!="")
                        {
                            if (Convert.ToInt32(txtPageNo.Text)==1)
                            {
                                txtPageNo.Visible = false;
                                btnGo.Visible = false;
                                btnPrevious.Visible = false;
                            }
                        }
                    }
                }
                else
                {
                    grdRoles.Visible = false;
                    SetVisibility(false);

                    btnCreate.Visible = true;
                    btnGo.Visible = false;
                    btnPrevious.Visible = false;
                    btnNext.Visible = false;
                    txtPageNo.Visible = false;

                    MassageSummery("IIS504");
                }

                if (roles.Count > 0)
                    return true;                
            }
            return false;
        }

        //private DataSet GetDatasetForList(List<UserRole_aspnet> list)
        //{
        //    DataSet ds = new DataSet();
        //    DataTable dt = new DataTable();
        //    DataColumn dc = new DataColumn("Role Name", Type.GetType("System.String"));
        //    dt.Columns.Add(dc);
        //    DataRow dr;

        //    foreach (UserRole_aspnet role in list)
        //    {
        //        dr = dt.NewRow();
        //        dr["Role Name"] = role.RoleName;
        //        dt.Rows.Add(dr);
        //    }
        //    return ds;
        //}

    }
}
